<template>
  <div id="app">
    <!-- 全局认证状态同步组件，确保登录状态始终与localStorage同步 -->
    <GlobalAuthSync />
    <router-view />
  </div>
</template>

<script setup>
import { onMounted, onBeforeUpdate, onUpdated } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from './stores/auth';
import GlobalAuthSync from './components/GlobalAuthSync.vue';
import axios from 'axios';

const router = useRouter();
const userStore = useUserStore();

// 核心的全局登录状态同步函数
const globalSyncLoginStatus = () => {
  console.log('App.vue - 执行全局登录状态同步');
  
  try {
    // 直接从localStorage读取数据
    const storedToken = localStorage.getItem('userToken');
    const storedUserInfo = localStorage.getItem('userInfo');
    const hasToken = !!storedToken;
    
    console.log('App.vue - 本地存储数据:', { hasToken, hasUserInfo: !!storedUserInfo });
    
    // 强制更新store状态
    userStore.token = storedToken || '';
    userStore.isLoggedIn = hasToken;
    
    if (hasToken && storedUserInfo) {
      try {
        userStore.userInfo = JSON.parse(storedUserInfo);
      } catch (e) {
        console.error('App.vue - 解析用户信息失败:', e);
      }
    }
    
    console.log('App.vue - 同步后登录状态:', {
      isLoggedIn: userStore.isLoggedIn,
      getIsLoggedIn: userStore.getIsLoggedIn,
      hasToken: !!userStore.token
    });
  } catch (error) {
    console.error('App.vue - 同步登录状态失败:', error);
  }
};

// 组件挂载时同步
onMounted(async () => {
  console.log('App.vue - 组件挂载');
  
  // 先执行基本的状态同步
  globalSyncLoginStatus();
  
  // 获取存储的信息
  const savedToken = localStorage.getItem('userToken');
  const savedUserInfo = localStorage.getItem('userInfo');
  const savedUserId = localStorage.getItem('userId') || (savedUserInfo ? JSON.parse(savedUserInfo).id : null);
  
  // 如果有token和用户ID，尝试从后端获取最新的用户信息
  if (savedToken && savedUserId) {
    try {
      console.log('App.vue - 尝试从后端获取最新用户信息，用户ID:', savedUserId);
      const response = await axios.get(`/api/users/${savedUserId}`);
      
      if (response.data && (response.data.code === 200 || response.data.success)) {
        const latestUserData = response.data.data;
        console.log('App.vue - 获取到最新用户信息:', latestUserData);
        // 更新localStorage中的用户信息
        localStorage.setItem('userInfo', JSON.stringify(latestUserData));
        // 更新store中的用户信息
        if (userStore.setUserInfo) {
          userStore.setUserInfo(latestUserData);
        } else {
          userStore.userInfo = latestUserData;
        }
        console.log('App.vue - 用户状态已更新:', { isLoggedIn: userStore.isLoggedIn, nickname: latestUserData?.nickname });
      }
    } catch (getInfoError) {
      console.warn('App.vue - 获取最新用户信息失败，使用本地存储的信息:', getInfoError);
    }
  }
  
  // 添加全局的storage事件监听，当localStorage变化时同步
  window.addEventListener('storage', (e) => {
    if (e.key === 'userToken' || e.key === 'userInfo' || e.key === null) {
      console.log('App.vue - localStorage变化，同步登录状态');
      globalSyncLoginStatus();
    }
  });
  
  // 添加全局的路由变化前监听
  router.beforeEach((to, from, next) => {
    console.log('App.vue - 路由变化前同步:', from.path, '->', to.path);
    globalSyncLoginStatus();
    next();
  });
  
  // 添加全局的路由变化后监听
  router.afterEach((to, from) => {
    console.log('App.vue - 路由变化后同步:', from.path, '->', to.path);
    setTimeout(() => {
      globalSyncLoginStatus();
    }, 0);
  });
});

// 组件更新前同步
onBeforeUpdate(() => {
  console.log('App.vue - 组件更新前');
  globalSyncLoginStatus();
});

// 组件更新后同步
onUpdated(() => {
  console.log('App.vue - 组件更新后');
  globalSyncLoginStatus();
});
</script>

<style>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
  Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  line-height: 1.6;
  color: #333;
}

#app {
  min-height: 100vh;
}
</style>